/**
 * Author: ling_feng
 * Date: 2018.5.23
 * CopyRight:
 * 通信注册监听类
 */

import MKSocket from './MKSocket'

export default class MKSocketObserver {
    public m_onConnect: Function;
    public m_onMessage: Function;
    public m_onClose: Function;
    public m_onError: Function;
    private m_handleMsg: Array<{ name: number, callback: (msgID: number, message: ArrayBuffer) => void }> = [];

    public constructor() {

    }

    onDestroy() {
        this.m_onConnect = null;
        this.m_onMessage = null;
        this.m_onClose = null;
        this.m_onError = null;
        this.m_handleMsg.length = 0;
    }

    /**
     * 回调处理
     * @param socket 
     */
    onConnect(socket: MKSocket) {
        if (this.m_onConnect != null) {
            this.m_onConnect(socket);
        }
    }

    onClose(socket: MKSocket) {
        if (this.m_onClose != null) {
            this.m_onClose(socket);
        }
    }

    onError(socket: MKSocket) {
        if (this.m_onError != null) {
            this.m_onError(socket);
        }
    }

    /**
     * 处理抛出消息
     * @param msgID 
     * @param message 
     */
    onMessage(msgID: number, message: ArrayBuffer): boolean {
        for (var i = 0; i < this.m_handleMsg.length; ++i) {
            var ele = this.m_handleMsg[i];
            if (ele.name === msgID) {
                ele.callback(msgID, message);
                return true;
            }
        }

        return false;
    }

    /**
     * 注册返回消息回调
     * @param msgID 
     * @param callback 
     */
    registerMsg(msgID: number, callback: (msgID: number, message: ArrayBuffer) => void) {
        for (var i = 0; i < this.m_handleMsg.length; ++i) {
            var ele = this.m_handleMsg[i];
            if (ele.name === msgID) {
                return;
            }
        }

        this.m_handleMsg.push({ name: msgID, callback: callback });
    }


    /**
     * 删除注册消息回调
     * @param msgID 
     */
    unRegisterMsg(msgID: number) {
        for (var i = 0; i < this.m_handleMsg.length; ++i) {
            var ele = this.m_handleMsg[i];
            if (ele.name === msgID) {
                this.m_handleMsg.splice(i, 1);
                return;
            }
        }
    }
}